<!--
 * @Description:
 * @version:
 * @Author: sunqian_sr
 * @Date: 2023-03-03 16:44:11
 * @LastEditors: Andy
 * @LastEditTime: 2023-04-06 15:19:39
-->
<template>
  <el-scrollbar class="form-panel capital-structure">
    <div class="form-box" v-for="(item, index) in ruleForm" :key="index">
      <div class="structure-title flex-row flex-between">
        <label>{{ $t('certification.enterprise.stockholder') }}{{ index + 1 }}</label>
        <div class="btn-group">
          <el-button type="text" @click="handleAddForm(index)" v-if="index === ruleForm.length - 1">
            <em class="el-icon-plus"></em>
            {{ $t('certification.enterprise.addStockholder') }}
          </el-button>
          <el-button type="text" @click="handleDeleteForm(index)" v-if="ruleForm.length > 1">
            <em class="el-icon-delete"></em>
            {{ $t('certification.enterprise.delStockholder') }}
          </el-button>
        </div>
      </div>
      <el-form
        :model="ruleForm[index]"
        :rules="rules"
        class="demo-form-inline border-bottom"
        :ref="'ruleFormRef' + index"
        label-position="top"
      >
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item :label="$t('certification.enterprise.stockholderName')" prop="name">
              <el-input
                v-model="item.name"
                maxlength="50"
                clearable
                :placeholder="$t('certification.enterprise.stockholderNamePlaceholder')"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item :label="$t('certification.enterprise.stockholderCurrency')" prop="currency">
              <x-select
                :placeholder="$t('certification.enterprise.stockholderCurrencyPlaceholder')"
                v-model="item.currency"
                :options="dictOptions['currency']"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('certification.enterprise.stockholderContribution')" prop="contributionAmount">
              <el-input
                v-model="item.contributionAmount"
                clearable
                maxlength="50"
                :placeholder="$t('certification.enterprise.stockholderContributionPlaceholder')"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('certification.enterprise.stockholderCountry')" prop="country">
              <x-select
                :placeholder="$t('certification.enterprise.stockholderCountryPlaceholder')"
                v-model="item.country"
                :options="dictOptions['country']"
                :attrOption="{
                  label: 'areaName',
                  value: 'areaName'
                }"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('certification.enterprise.stockholderProportion')" prop="shareholdingProportion">
              <el-input
                v-model="item.shareholdingProportion"
                clearable
                maxlength="50"
                :placeholder="$t('certification.enterprise.stockholderProportionPlaceholder')"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('certification.enterprise.industryAffiliation')" prop="industry">
              <x-select-tree
                v-model="item.industry"
                :ref="'selectTree' + index"
                :is-lazy="true"
                :nodeKey="'dictCode'"
                :request-url="'/srm/dict/tree/findTree'"
                :othe-params="{ dictType: 'industry' }"
                :placeholder="$t('certification.enterprise.industryAffiliationPlaceholder')"
                :defaultProps="industryProps"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('certification.enterprise.stockholdeType')" prop="shareholderType">
              <x-select
                :placeholder="$t('certification.enterprise.istockholdeTypePlaceholder')"
                v-model="item.shareholderType"
                :options="dictOptions['shareholder_type']"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item :label="$t('certification.enterprise.mainBusiness')" prop="mainBusiness">
              <el-input
                type="textarea"
                v-model="item.mainBusiness"
                style="width: 100%"
                maxlength="200"
                :placeholder="$t('certification.enterprise.mainBusinessPlaceholder')"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item :label="$t('certification.enterprise.stockholdeFiles')" prop="capitalFiles">
              <!-- 股东附件 -->
              <x-upload
                :ref="'fileUpload' + index"
                :edit-flag="true"
                :limit="9"
                :fileSize="20"
                :old-file-list="item.capitalFiles || []"
                :file-type="['jpg', 'jpeg', 'png', 'ppt', 'pptx', 'pdf', 'xls', 'xlsx']"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
  </el-scrollbar>
</template>
<script>
  import { cloneDeep } from '@package/utils'
  import { apiPostAddCapital, apiGetCapital, apiPostUpdateCapital } from '../api'
  import { EnumApiCode } from '../../../../../../globalEnum.js'

  export default {
    name: 'CapitalStructure',
    props: {
      dictOptions: {
        type: Object,
        default: () => ({})
      },
      supplierId: {
        type: String
      }
    },
    data() {
      return {
        ruleForm: [
          {
            name: '',
            country: '',
            contributionAmount: '',
            currency: '',
            shareholdingProportion: '',
            industryCode: '',
            industry: {
              dictName: '',
              dictCode: ''
            },
            shareholderType: '',
            capitalFiles: [],
            mainBusiness: ''
          }
        ],
        rules: {
          name: [
            { required: true, message: this.$t('certification.enterprise.stockholderNamePlaceholder'), trigger: 'blur' }
          ],
          contributionAmount: [
            {
              required: true,
              message: this.$t('certification.enterprise.stockholderContributionPlaceholder'),
              trigger: 'blur'
            }
          ],
          currency: [
            {
              required: true,
              message: this.$t('certification.enterprise.stockholderCurrencyPlaceholder'),
              trigger: ['blur', 'change']
            }
          ],
          shareholdingProportion: [
            {
              required: true,
              message: this.$t('certification.enterprise.stockholderProportionPlaceholder'),
              trigger: ['blur', 'change']
            }
          ]
        },
        industryProps: {
          label: 'dictName',
          value: 'dictCode',
          children: 'children'
        }
      }
    },
    watch: {
      supplierId: {
        handler(val) {
          if (val) {
            this.getDetail()
          }
        },
        immediate: true,
        deep: true
      }
    },
    methods: {
      async getDetail() {
        const { data } = await apiGetCapital(this.supplierId)
        this.$nextTick(() => {
          this.ruleForm = data && data?.length ? cloneDeep(data) : this.ruleForm
          this.ruleForm = this.ruleForm.map((v) => {
            return {
              ...v,
              industry: {
                dictCode: v.industryCode,
                dictName: v.industryCategory
              }
            }
          })
        })
      },
      handleAddForm(index) {
        this.$refs[`ruleFormRef${index}`][0].validate((valid) => {
          if (valid) {
            this.ruleForm.push({
              name: '',
              country: '',
              contributionAmount: '',
              currency: '',
              shareholdingProportion: '',
              industryCode: '',
              industry: {
                dictCode: '',
                dictName: ''
              },
              mainBusiness: '',
              shareholderType: '',
              capitalFiles: []
            })
          } else {
            this.$message.error(this.$t('certification.enterprise.tipsError'))
          }
        })
      },
      handleDeleteForm(index) {
        this.$confirm('确定是否删除该股东数据?', '提示', {
          confirmButtonText: this.$t('common.sure'),
          cancelButtonText: this.$t('common.cancel'),
          type: 'warning'
        }).then(() => {
           this.ruleForm.splice(index, 1)
        })
      },
      handleVaildForm() {
        return new Promise((resolve) => {
          const vaildArr = []
          for (let index = 0; index < this.ruleForm.length; index++) {
            this.$refs[`ruleFormRef${index}`][0].validate((valid) => {
              if (valid) {
                vaildArr.push(1)
              }
            })
          }
          if (vaildArr.length === this.ruleForm.length) {
            return resolve(true)
          }
          return resolve(false)
        })
      },
      onSumit(isVaild = true) {
        return new Promise(async (resolve, reject) => {
          const isSubmit = !isVaild || (await this.handleVaildForm())
          if (isSubmit) {
            const param = this.ruleForm.map((v, vIndex) => {
              const { fileList } = this.$refs[`fileUpload${vIndex}`][0]
              const data = v
              return {
                ...v,
                capitalFiles: fileList?.length
                  ? fileList.map((item) => {
                      return {
                        fileName: item.name || item.fileName,
                        filePath: item.filePath || item.response.data.filePath,
                        fileType: (item.name || item.fileName).slice((item.name || item.fileName).lastIndexOf('.') + 1),
                        remark: item.remark
                      }
                    })
                  : [],
                supplierId: this.supplierId,
                industryCategory: data.industry.dictName,
                industryCode: data.industry.dictCode
              }
            })
            // 判断股东数据有无ID
            const isEdit = param.some((v) => 'id' in v)
            try {
              const { data, code } = isEdit ? await apiPostUpdateCapital(param) : await apiPostAddCapital(param)
              if (EnumApiCode.Success === code) {
                // this.getDetail()
                resolve(data)
              } else {
                reject()
              }
            } finally {
              reject()
            }
          } else {
            reject()
          }
        })
      }
    }
  }
</script>
